import { Ref } from "@vue/reactivity";

function useTouchEvent(touchID: string, pageID: string, status: Ref<string>) {
    let startY: number = 0, raf, ticking = false, time = 0, now: number;
    const DEFAULT_OFFSET_Y = 100;

    const touchStartEvent = (ev: TouchEvent) => {
      if ( status.value === 'groups' ) { 
        now = Date.now(); 
        time = 0;
        startY = ev.targetTouches[0].clientY;
      }
    }
  
    const touchMoveEvent = (ev: TouchEvent) => {
      if ( status.value === 'groups' && !ticking) {
        const pageDom = document.getElementById(pageID);

        let clientY = ev.targetTouches[0].clientY;
        
        raf = requestAnimationFrame(() => {

          pageDom && (pageDom.style.transform = `translateY(${clientY - startY}px)`)
          ++time;
          ticking = false;
        })
        ticking = true;
      } 
    }
    
    const touchEndEvent = (ev: TouchEvent) => {
      const pageDom = document.getElementById(pageID);
      const touchDom = document.getElementById(touchID+'-img');
        
      raf = requestAnimationFrame(() => {
        if ( status.value === 'groups' ) {
          let element = ev.changedTouches[0];
          if ( element.clientY - startY > DEFAULT_OFFSET_Y) {
            console.log('end');
            console.log('帧数：',time, '，毫秒数：',Date.now() - now);
            pageDom && (pageDom.style.transform = `translateY(80vh)`)
            
            if ( touchDom ) {
              touchDom.style.width = '5vh';
              touchDom.style.height = '5vh';
              touchDom.style.borderRadius = '3vh';
            }
            
            status.value = 'teams';
          } else {
            pageDom && (pageDom.style.transform = `translateY(0px)`)
          }
        } else {
          if ( touchDom ) {
            touchDom.style.width = '';
            touchDom.style.height = '';
            touchDom.style.borderRadius = '';
          }
          status.value = 'groups'
          pageDom && (pageDom.style.transform = `translateY(0px)`)
        }
      })

    }

    return [touchStartEvent, touchMoveEvent, touchEndEvent];
}

export default useTouchEvent;